# -*- coding: utf-8 -*-
"""
@Time ： 2022/12/29 20:42
@Author ： PJC
"""
import logging, time, os
from functools import wraps
import traceback


class ColorHandler(logging.StreamHandler):
    """彩色日志，根据不同级别的日志显示不同颜色"""

    def emit(self, record):
        try:
            msg = self.format(record)
            if record.levelno == 10:
                print('\033[0;36m%s\033[0m' % msg)  # 绿色
            elif record.levelno == 20:
                print('\033[0;32m%s\033[0m' % msg)  # 青蓝色
            elif record.levelno == 30:
                print('\033[0;34m%s\033[0m' % msg)  # 蓝色
            elif record.levelno == 40:
                print('\033[0;31m%s\033[0m' % msg)  # 紫红色
            elif record.levelno == 50:
                print('\033[0;31m%s\033[0m' % msg)  # 血红色
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)


"""header是什么"""
# logger日志模块中的类
# 用来自定义日志对象的规则（比如设置日志输出格式，等级等）
# 常用子类： StreamHandler, FileHandler
# StreamHandler 控制台输出日志
# FileHandler 日志输出到文件
BASE_PATH = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
# print(BASE_PATH)
# 日志文件路径
LOG_PATH = os.path.join(BASE_PATH, "log")
# print(LOG_PATH)
if not os.path.exists(LOG_PATH):
    os.makedirs(LOG_PATH)


class Logger():

    def __init__(self):
        self.logname = os.path.join(LOG_PATH, '{}.log'.format(time.strftime('%y-%m-%d')))
        # 创建一个log日志
        self.logger = logging.getLogger('log')
        # 设置日志默认级别
        self.logger.setLevel(logging.DEBUG)
        # 创建日志格式对象
        self.formatter = logging.Formatter(
            '\n[%(asctime)s]\t[%(filename)s %(lineno)d]\t[%(levelname)s]: %(message)s'
        )
        # 创建FileHandler对象
        self.filelogger = logging.FileHandler(self.logname, mode='a', encoding='UTF-8')

        # 创建StreamHeader对象
        # self.console = logging.StreamHandler()
        self.console = ColorHandler()

        # 创建FileHandler对象自定义日志级别
        self.console.setLevel(logging.DEBUG)
        self.filelogger.setLevel(logging.DEBUG)

        # 设置两个地方的日志格式
        self.filelogger.setFormatter(self.formatter)
        self.console.setFormatter(self.formatter)

        # logger日志对象加载FileHandler对象
        self.logger.addHandler(self.filelogger)

        # logger日志对象加载StreamHeader对象
        self.logger.addHandler(self.console)


Logger = Logger().logger


def logger(func):
    @wraps(func)
    def log(*args, **kwargs):
        Logger.info(f"--------开始执行{func.__name__}用例--------")
        try:
            func(*args, **kwargs)
        except Exception as e:
            Logger.error(f"--------{func.__name__}用例执行失败，失败原因：--------")
            Logger.error(f"{func.__name__}用例 is error, here are details:{traceback.format_exc()}")
            raise e
        else:
            Logger.info(f"--------{func.__name__}执行成功--------")

    return log


@logger
def a():
    assert 2 == 2


@logger
def b():
    assert 2 == 3



@logger
def c():
    assert 2 == 2


if __name__ == '__main__':
    a()
    b()
    c()
